﻿using Elasticsearch.Net;
using ElasticSearchDemo.Models;
using ElasticSearchDemo.Models.Dto;
using ElasticSearchDemo.Service;
using HtmlAgilityPack;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Nest;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace ElasticSearchDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private readonly IESServer _eSServer;

        public HomeController(ILogger<HomeController> logger, IESServer eSServer)
        {
            _logger = logger;
            _eSServer = eSServer;
        }

        [HttpGet]
        public async Task<IActionResult> Index(string keyword)
        {

            //ISearchResponse<Product> response = await _eSServer.ElasticLinqClient.SearchAsync<Product>(p => p.Index("product").Query(q => q.MatchAll()).Size(100));

            //ViewBag.ProductList = response.Documents.ToList();

            if (string.IsNullOrWhiteSpace(keyword))
            {
                ViewBag.ProductList = new List<Product>();
                ViewBag.KeyWord = "天虹";

                return View();
            }


            //ISearchResponse<Product> response = await _eSServer.ElasticLinqClient.SearchAsync<Product>(p => p.Index("product").Query(q => q.Bool(a =>
            //    a.Should(a =>
            //    a.Match(a => a.Field(a => a.ProductName)
            //    .Query(keyword)),
            //    a => a.Match(a => a.Field(a => a.ShopName)
            //    .Query(keyword)))))
            //    .Sort(a => a.Ascending(a => a.Price))
            //    .Highlight(a => a.PreTags("<em style='color:red;' >").PostTags("</em>").Fields(a => a.Field(a => a.ProductName), a => a.Field(a => a.ShopName)
            //      )
            //    )
            //    .Size(1024)
            //);


            ISearchResponse<Product> response = await _eSServer.ElasticLinqClient.SearchAsync<Product>(p => p.Index("product")
                    .Query(q => q.MultiMatch(a => a.Query(keyword).Fields(a => a.Field(a => a.ProductName).Field(a => a.ShopName))))
                    .Sort(a => a.Ascending(a => a.Price))
                    .Highlight(a => a.RequireFieldMatch(false).PreTags("<em style='color:red;' >").PostTags("</em>").Fields(a => a.Field(a => a.ProductName), a => a.Field(a => a.ShopName)))
                    .Aggregations(a => a.ValueCount("aggs_value_count", a => a.Field(a => a.Id).Missing(0))) //聚合搜索到的总记录数
                    .From(0)
                    .Size(30)
            );

            //搜索到的总记录数
            double? count=((ValueAggregate)response.Aggregations["aggs_value_count"]).Value;


            //var productList = response.Documents.ToList();


            List<Product> productList = new List<Product>();

            var highlightList = response.HitsMetadata.Hits.Select(s => new { s.Source, s.Highlight }).ToList();

            foreach (var item in highlightList)
            {
                Product product = item.Source;

                var highlight = item.Highlight;

                if (highlight.ContainsKey("shop_name"))
                {
                    product.ShopName = highlight["shop_name"].FirstOrDefault();
                }

                if (highlight.ContainsKey("product_name"))
                {
                    product.ProductName = highlight["product_name"].FirstOrDefault();
                }

                productList.Add(product);


            }

            ViewBag.ProductList = productList;
            ViewBag.KeyWord = keyword;

            return View();
        }


        #region 多条件查询拼接查询
        public async Task<IActionResult> QueryProductTest()
        {
            SearchCondition searchCondition = new SearchCondition()
            {
                StartDate = new DateTime(2021, 4, 5, 0, 0, 0),
                EndDate = new DateTime(2021, 4, 5, 23, 59, 59),
                Price = 10,
                ProductName = "电脑",
                ShopName = "天虹",
                IsNew = true
            };


            return Ok(await QueryProductAsync(searchCondition, 1, 50));
        }


        public async Task<PagedResult<Product[]>> QueryProductAsync(SearchCondition condition, int pageIndex, int pageSize)
        {
            var query = this.BuildQueryContainer(condition);

            ISearchResponse<Product> response = await _eSServer.ElasticLinqClient.SearchAsync<Product>(s => s
                  .Index("product")
                  .From((pageIndex - 1) * pageSize)
                  .Size(pageSize)
                  .Query(q => query)
                  .Sort(st => st.Descending(d => d.CreateTime))
                );


            var list = response.Documents.ToList();

            if (response.ApiCall.Success)
            {
                return new PagedResult<Product[]>
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    Total = response.Total,
                    ReturnObj = response.Hits.Select(s => s.Source).ToArray()
                };
            }

            return new PagedResult<Product[]> { IsSuccess = false };
        }


        /// <summary>
        /// 多查询条件拼接
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public QueryContainer BuildQueryContainer(SearchCondition condition)
        {
            var queryCombin = new List<Func<QueryContainerDescriptor<Product>, QueryContainer>>();

            //全文搜索
            if (!string.IsNullOrWhiteSpace(condition.ProductName))
            {
                queryCombin.Add(mt => mt.Match(m => m.Field(t => t.ProductName).Query(condition.ProductName)));
            }

            //数值区间匹配
            if (condition.Price.HasValue)
            {
                queryCombin.Add(mt => mt.Range(m => m.Field(t => t.Price).GreaterThanOrEquals(double.Parse(condition.Price.Value.ToString()))));
            }

            //提示：Match 和 MatchPhrase 的区别，例如对于"长宁区"
            //1.Match 会将"长宁区"进行分词匹配，例如只要包含"区"的数据（比如静安区），也会被查询命中
            //2.MatchPhrase 则可以理解为短语匹配，只有当数据包含“长宁区”完整短语的数据，才会被查询命中

            //短语匹配
            if (!string.IsNullOrWhiteSpace(condition.ShopName))
            {
                queryCombin.Add(mt => mt.MatchPhrase(m => m.Field(t => t.ShopName).Query(condition.ShopName)));
            }

            //精确匹配
            if (condition.IsNew.HasValue)
            {
                queryCombin.Add(mt => mt.Term(m => m.Field(t => t.IsNew).Value(condition.IsNew)));
            }

            return Query<Product>.Bool(b => b
                .Must(queryCombin)
                .Filter(f => f
                    .DateRange(dr => dr.Field(t => t.CreateTime)  //时间范围匹配
                    .GreaterThanOrEquals(DateMath.Anchored(condition.StartDate.ToString("yyyy-MM-ddTHH:mm:ss")))
                    .LessThanOrEquals(DateMath.Anchored(condition.EndDate.ToString("yyyy-MM-ddTHH:mm:ss")))
                    )
                )
            );
        }


        #endregion



        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }


        /// <summary>
        /// Linq方式
        /// </summary>
        /// <param name="eSSever"></param>
        /// <returns></returns>
        public async Task<List<Persons>> ELasticTest()
        {
            var list = await _eSServer.ElasticLinqClient.SearchAsync<Persons>(p => p.Index("persons").Query(q => q
              .Match(m => m
                 .Field(f => f.EnterpriseName)
                 .Query("责任公司")
              )
            )
          );


            return list.Documents.ToList();
        }

        /// <summary>
        /// Json方式
        /// </summary>
        /// <param name="eSServer"></param>
        /// <returns></returns>
        public async Task<IActionResult> ElasticTest2()
        {

            var postData = PostData.Serializable(new
            {
                from = 0,
                size = 10,
                query = new
                {
                    match = new
                    {
                        enterprise_name = new
                        {
                            query = "责任公司"
                        }
                    }
                }
            });

            StringResponse searchResponse = await _eSServer.ElasticJsonClient.SearchAsync<StringResponse>("persons", postData);

            var successful = searchResponse.Success;
            var responseJson = searchResponse.Body;

            return Ok(responseJson);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Add()
        {
            Persons persons = new Persons();
            persons.Id = 121;
            persons.Age = 15;
            persons.Name = "你好啊,兄嘚!123668";
            persons.CreateTime = DateTime.Now;


            #region 方法一：通过委托
            //同步
            //IndexResponse indexResponse = _eSServer.ElasticLinqClient.Index(persons,a=>a.Index("persons"));

            //异步
            //IndexResponse indexResponse = _eSServer eSServer.ElasticLinqClient.IndexAsync(persons, a => a.Index("persons"));
            #endregion


            #region 方法二：通过 IndexRequest 对象
            //IndexResponse indexResponse = _eSServer.ElasticLinqClient.Index(new IndexRequest<Persons>(persons, "persons"));

            IndexResponse indexResponse = await _eSServer.ElasticLinqClient.IndexAsync(new IndexRequest<Persons>(persons, "persons"));
            #endregion


            if (indexResponse.IsValid)
            {
                return Ok("添加成功");
            }


            return Ok("添加失败");
        }

        /// <summary>
        /// 更新(反正这个版本这个更新也是:POST index/_doc/_id/_update)
        /// </summary>
        /// <param name="eSServer"></param>
        /// <returns></returns>
        public async Task<IActionResult> Update()
        {
            Persons persons = new Persons();
            persons.Id = 111;
            persons.Name = "张三三";
            persons.Age = 666;
            persons.EnterpriseName = "金开";


            DocumentPath<Persons> documentPath = new DocumentPath<Persons>(persons.Id);

            UpdateResponse<Persons> response = await _eSServer.ElasticLinqClient.UpdateAsync<Persons>(documentPath, t => t.Index("persons").Doc(persons));

            if (response.IsValid)
            {
                return Ok("更新成功");
            }

            return Ok("更新失败");
        }

        /// <summary>
        /// 指定部分更新
        /// </summary>
        /// <param name="eSServer"></param>
        /// <returns></returns>
        public async Task<IActionResult> UpdatePart()
        {
            Persons partialEntity = new Persons()
            {
                EnterpriseName = "Welcome to jinkaiwuianwang!"
            };

            IUpdateRequest<Persons, Persons> request = new UpdateRequest<Persons, Persons>("persons", "100")
            {
                Doc = partialEntity
            };

            UpdateResponse<Persons> response = await _eSServer.ElasticLinqClient.UpdateAsync(request);

            if (response.IsValid)
            {
                return Ok("更新成功");
            }

            return Ok("更新失败");
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Test()
        {
            #region 测试添加
            //Persons persons = new Persons();
            //persons.Id = 112;
            //persons.Name = "我是哦哦哦";
            //persons.Age = 22;
            //persons.EnterpriseName = "市公安局2分局";
            //persons.CreateTime = DateTime.Now;

            //CreateResponse response= await _eSServer.AddAsync<Persons>(persons,nameof(persons),persons.Id.ToString());

            //if (response.IsValid)
            //{
            //    Console.WriteLine("添加成功!");
            //}
            //else
            //{
            //    Console.WriteLine("添加失败");
            //}
            #endregion

            #region 测试获取一个文档

            //GetResponse<Persons> getPersons = await _eSServer.GetAsync<Persons>("persons", "112");

            //Persons pObj = getPersons.Source;
            //long version = getPersons.Version;
            #endregion

            #region 测试更新

            //Persons persons = new Persons();
            //persons.Id = 112;
            //persons.Name = "分局空间集聚就";

            //UpdateResponse<Persons> updateResponse=await _eSServer.UpdateAsync<Persons>(persons,"persons",persons.Id.ToString());

            //if (updateResponse.IsValid)
            //{
            //    Console.WriteLine("更新成功!");
            //}
            //else
            //{
            //    Console.WriteLine("更新失败");
            //}

            #endregion

            #region 测试删除

            //DeleteResponse deleteResponse=await _eSServer.DeleteAsync("persons","112");

            //if (deleteResponse.IsValid)
            //{
            //    Console.WriteLine("删除成功!");
            //}
            //else
            //{
            //    Console.WriteLine("删除失败");
            //}

            #endregion

            #region 测试SQL
            //DataTable dt=_eSServer.GetDataBySql("select * from persons order by id desc limit 5");

            #endregion

            #region DeleteByQueryAsync
            //删除某字段中含有null的所有文档
            //POST persons/_delete_by_query?scroll_size=5000
            //{
            //    "query": {
            //        "bool": {
            //            "must_not": {
            //                "exists": {
            //                    "field": "Id"
            //                }
            //            }
            //        }
            //    }
            //}

            //await _eSServer.ElasticLinqClient.DeleteByQueryAsync<Persons>(d => d
            //.Index("persons")
            //.Query(a => a.Bool(a => a.MustNot(a => a.Exists(a => a.Field(a => a.Id))))));



            ////删除Id>=0 and Id< 100 的所有文档
            //await _eSServer.ElasticLinqClient.DeleteByQueryAsync<Persons>(d => d.Query(q => q
            //      .Range(r => r
            //          .Field(f => f.Id)
            //          .GreaterThanOrEquals(0)
            //          .LessThan(100)
            //      )
            //));
            #endregion

            #region 测试批量添加
            //List<Persons> persons = new List<Persons>();

            //persons.Add(new Persons()
            //{
            //    Id = 1,
            //    Age = 19,
            //    CreateTime = DateTime.Now,
            //    EnterpriseName = "heihei",
            //    Name = "zzz"
            //});

            //persons.Add(new Persons()
            //{
            //    Id = 2,
            //    Age = 20,
            //    CreateTime = DateTime.Now,
            //    EnterpriseName = "heihei2",
            //    Name = "zzz111"
            //});

            //BulkResponse bulkResponse = await _eSServer.AddRangeAsync(persons, "persons");

            //if (bulkResponse.IsValid)
            //{
            //    return Ok("success");
            //}
            //else
            //{
            //    return Ok("failed");
            //}

            #endregion



            return Ok("操作完成!");
        }


        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> InitData()
        {

            await _eSServer.DeleteIndexAsync("product");

            CreateIndexResponse createIndexResponse = _eSServer.ElasticLinqClient.Indices.Create("product", a => a.Map<Product>(m => m.AutoMap()));

            if (createIndexResponse.IsValid)
            {
                Console.WriteLine("创建索引成功!");
            }


            string url = "https://search.jd.com/Search?keyword=pc%E7%94%B5%E8%84%91&enc=utf-8&wq=pc%E7%94%B5%E8%84%91&pvid=f90f1fa87ff145fda50239058242a923";

            HtmlWeb web = new HtmlWeb();

            //从url中加载
            HtmlDocument doc = web.Load(url);

            var aNode = doc.DocumentNode.SelectNodes("//div[@id='J_goodsList']/ul/li");

            long i = 1;

            List<Product> list = new List<Product>();

            Product product = null;

            Random random = new Random();

            foreach (HtmlNode item in aNode)
            {
                var price = item.Descendants("strong")?.FirstOrDefault().Descendants("i").FirstOrDefault().InnerText;

                var productName = item.Descendants("div").Where(a => a.Attributes["class"] != null && a.Attributes["class"].Value == "p-name p-name-type-2")
                    .FirstOrDefault()?.Descendants("em")?.FirstOrDefault().InnerText.Replace("\r\n", "").Replace("\t\n", "");

                var img = item.Descendants("img")?.FirstOrDefault().GetAttributeValue("data-lazy-img", "");


                var shopName = item.Descendants("a").Where(a => a.Attributes["class"] != null && a.Attributes["class"].Value == "curr-shop hd-shopname").FirstOrDefault().InnerText;


                product = new Product();
                product.Id = i;
                product.CreateTime = DateTime.Now;
                product.Evaluate = random.Next(0, 1024);
                product.Img = img;
                product.Popularity = random.Next(0, 1024);
                product.Price = decimal.Parse(price);
                product.ProductName = productName;
                product.Sales = random.Next(0, 1024);
                product.IsNew = random.Next(0, 2) == 1 ? true : false;
                product.ShopName = shopName;


                list.Add(product);

                i++;


                //Console.WriteLine(productName.Replace("\r\n","").Replace("\t\n",""));
                //Console.WriteLine(shopName);
                //Console.WriteLine(price);
                //Console.WriteLine(img);


                //Console.WriteLine("=============================================================");



                //foreach (var item2 in productName)
                //{
                //    if (item2.Attributes["class"]!=null && item2.Attributes["class"].Value=="p-name p-name-type-2")
                //    {
                //        Console.WriteLine(item2.Attributes["class"].Value);
                //    }


                //}

                //HtmlNode node = item.SelectSingleNode("//div[@class='p-name p-name-type-2']/em");
            }


            BulkResponse response = await _eSServer.ElasticLinqClient.IndexManyAsync<Product>(list, "product");

            if (response.IsValid)
            {
                return Ok("初始化数据成功!");
            }
            else
            {
                return Ok("初始化数据失败!");
            }

        }



        #region 地理位置GEO
        public IActionResult GeoDemo()
        {
            //_eSServer.ElasticLinqClient.Search<Persons>(a => a.Query(a => a.Bool(a => a.Filter(a => a.GeoDistance(a => a.Distance())))));

            //_eSServer.ElasticLinqClient.Search<Persons>(a => a.Query(a => a.Bool(a => a.Filter(a => a.GeoBoundingBox()))));


            #region 初始化数据
            //PUT geo
            //{
            //   "mappings": {
            //        "properties": {
            //            "name":{
            //                "type":"keyword"
            //            },
            //            "location":{
            //                "type": "geo_point"
            //            }
            //        }
            //    }
            //}

            //double [] Location 类型 映射的必须是如下格式插入的数据
            //PUT geo/_doc/1
            //{
            //  "name":"西安",
            //  "location":[108.939621,34.343147]
            //}

            //POST _bulk
            //{ "index":{ "_index":"geo","_id":1} }
            //{ "name":"西安","location":[108.939621,34.343147]}
            //{ "index":{ "_index":"geo","_id":2} }
            //{ "name":"北京","location":[116.322056,39.89491]}
            //{ "index":{ "_index":"geo","_id":3} }
            //{ "name":"上海","location":[121.473658,31.230378]}
            //{ "index":{ "_index":"geo","_id":4} }
            //{ "name":"天津","location":[117.201538,39.085294]}
            //{ "index":{ "_index":"geo","_id":5} }
            //{ "name":"杭州","location":[120.209947,30.245853]}
            //{ "index":{ "_index":"geo","_id":6} }
            //{ "name":"武汉","location":[114.305215,30.592935]}
            //{ "index":{ "_index":"geo","_id":7} }
            //{ "name":"合肥","location":[117.227308,31.82057]}
            //{ "index":{ "_index":"geo","_id":8} }
            //{ "name":"重庆","location":[106.550464,29.563761]}
            #endregion


            var GeoSearch = _eSServer.ElasticLinqClient.Search<Geo>(s => s.Index("geo").From(0).Size(20).Query(
                      q => q.Bool(
                      b => b.Must(
                               f => f.GeoDistance(
                                g => g.Distance(600, DistanceUnit.Kilometers).Location(34.343147, 108.939621).Field(a => a.Location))))));

            return Ok(GeoSearch.Documents.ToList());
        }

        public async Task<IActionResult> InitGeo()
        {
            Geo2 geo2 = new Geo2();
            geo2.Id = 100;
            geo2.Name = "测试";
            geo2.Location = new GeoLocation(36.343147, 110.939621);

            CreateResponse response = await _eSServer.AddAsync<Geo2>(geo2, "geo2", geo2.Id.ToString());

            if (response.IsValid)
            {
                return Ok("init ok");
            }
            return Ok("init failed");
        }



        /// <summary>
        /// 推荐使用GEO的方式
        /// </summary>
        /// <returns></returns>
        public IActionResult GeoDemo2()
        {

            #region 初始化数据
            //PUT geo2
            //{
            //   "mappings": {
            //        "properties": {
            //            "name":{
            //                "type":"keyword"
            //            },
            //            "location":{
            //                "type": "geo_point"
            //            }
            //        }
            //    }
            //}

            //GeoLocation类型 映射的必须是如下格式插入的数据
            //PUT geo2/_doc/1
            //{
            //  "name":"西安",
            //  "location":{
            //    "lat": 34.27,
            //    "lon": 108.94
            //  }
            //}


            //POST _bulk
            //{ "index":{ "_index":"geo2","_id":1} }
            //{ "name":"西安","location":{ "lon":108.939621,"lat":34.343147} }
            //{ "index":{ "_index":"geo2","_id":2} }
            //{ "name":"北京","location":{ "lon":116.322056,"lat":39.89491} }
            //{ "index":{ "_index":"geo2","_id":3} }
            //{ "name":"上海","location":{ "lon":121.473658,"lat":31.230378} }
            //{ "index":{ "_index":"geo2","_id":4} }
            //{ "name":"天津","location":{ "lon":117.201538,"lat":39.085294} }
            //{ "index":{ "_index":"geo2","_id":5} }
            //{ "name":"杭州","location":{ "lon":120.209947,"lat":30.245853} }
            //{ "index":{ "_index":"geo2","_id":6} }
            //{ "name":"武汉","location":{ "lon":114.305215,"lat":30.592935} }
            //{ "index":{ "_index":"geo2","_id":7} }
            //{ "name":"合肥","location":{ "lon":117.227308,"lat":31.82057} }
            //{ "index":{ "_index":"geo2","_id":8} }
            //{ "name":"重庆","location":{ "lon":106.550464,"lat":29.563761} }
            #endregion

            #region geo_distance query
            //半径600公里范围的城市
            ISearchResponse<Geo2> response = _eSServer.ElasticLinqClient.Search<Geo2>(a => a.Index(Indices.Parse("geo2")).Query(a => a.GeoDistance(a =>
                      a.Field(a => a.Location)
                      .DistanceType(GeoDistanceType.Arc)
                      .Distance(600, DistanceUnit.Kilometers)
                      .Location(34.343147, 108.939621)
            )));
            #endregion

            #region geo_bounding_box_query
            //以南京经纬度作为矩形的左上角,以舟山经纬度作为矩形的右下角,构造出来的矩形中包含上海和杭州的两个城市
            ISearchResponse<Geo2> response2 = _eSServer.ElasticLinqClient.Search<Geo2>(a => a.Index("geo2")
            .Query(a => a.GeoBoundingBox(a => a.Field(a => a.Location)
              .BoundingBox(a => a.TopLeft(32.0639555, 118.7896728).BottomRight(29.9882446, 122.2064208)))));
            #endregion

            #region geo_polygon query
            //这里坐标是以包含武汉范围的画了一个三角形
            ISearchResponse<Geo2> response3 = _eSServer.ElasticLinqClient.Search<Geo2>(a => a.Index("geo2")
              .Query(a => a.GeoPolygon(a => a.Field(a => a.Location)
                .Points(new[] { new GeoLocation(31.79375558, 113.8238525), new GeoLocation(30.0072739, 114.224853), new GeoLocation(30.0072739235, 114.834594) })
              )));
            #endregion

            #region geo_shape query
            //查询某一个图形中是否包含该线:  
            //这里用的是矩形:envelope,是无锡到舟山两点之间的矩形是否包含上面苏州到上海这条线
            ISearchResponse<GeoShape> response4 = _eSServer.ElasticLinqClient.Search<GeoShape>(a => a.Index("geo_shape")
            .Query(a => a.GeoShape(a =>
              a.Shape(s => s.Envelope(new[] { new GeoCoordinate(31.587894464070395, 120.30029296875), new GeoCoordinate(29.973970240516614, 122.20642089843749) }))
              .Relation(GeoShapeRelation.Within)))
            );
            #endregion

            return Ok(response4.Documents.ToList());
        }
        #endregion


        #region 聚合 Bucket Aggregation

        public async Task<IActionResult> TermsAggregation()
        {
            //根据是否新品进行桶聚合
            ISearchResponse<Product> response=await _eSServer.ElasticLinqClient.SearchAsync<Product>(p=>p.Index("product")
                .Aggregations(a=>a.Terms("is_new_aggs",a=>a.Field(a=>a.IsNew)
                    .Aggregations(a=>a.Average("price_avg",a=>a.Field(a=>a.Price))
                    .Sum("price_sum",a=>a.Field(a=>a.Price))
                    )
                ))
            );

            var is_new_aggs = response.Aggregations.Terms("is_new_aggs");

            foreach (var item in is_new_aggs.Buckets)
            {
                Console.WriteLine($"{item.KeyAsString},{item.DocCount},{item.Average("price_avg").Value},{item.Sum("price_sum").Value}");
                
            }

           return  Ok();
        }

        #endregion




    }
}
